package com.sinoglobal.shakeprize.utils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.sinoglobal.shakeprize.activity.ShakeActivity;
import com.sinoglobal.shakeprize.activity.ShakeSessionActivity;
import com.sinoglobal.shakeprize.bean.ResponseShakeSessionList;
import com.sinoglobal.shakeprize.utils.OKhttpUtil.ResponseCallback;

import okhttp3.Request;

/**
 * @author temulu
 * @createdate 2015-8-31下午5:51:45
 * @Description 点击摇一摇 分发跳转帮助类
 */
public class DispatchIntentHelper {
	private static final int SERVICES_EXCEPTION = -2;
	private static final int REQUEST_EXCEPTION = -3;

	private static boolean accessible = true;// 是否可以访问网络

	public static void dispatchIntent(final Context context,String userId) throws URISyntaxException {
		if (!accessible) {
			return;
		}
		accessible = false;
		// 判断用户是否登录
		if (TextUtils.isEmpty(userId)) {
			context.startActivity(new Intent("com.sinoglobal.ningxia.Login"));
			accessible = true;
			return;
		}
		Map<String, Object> request = new HashMap<String, Object>();
		request.put("userId", userId);
		request.put("productCode", Contstent.PRODUCT_IDENTIFICATION);
		request.put("orderBy", "0");
		String url = Contstent.SHAKE_PATH + "yaoyiyao/roundList.do?json="
				+ JSON.toJSONString(request);
		OKhttpUtil.enqueue(url, new ResponseCallback() {

			private ResponseShakeSessionList responseList;

			@Override
			public void onFailure(Request arg0, IOException arg1) {
				Toast.makeText(context, "访问网络失败", Toast.LENGTH_SHORT).show();
				accessible = true;
			}

			@Override
			public void onResponse(String json) throws IOException {
				ItktLog.e("Response: "+json);
				try {
					responseList = JSON.parseObject(json,
							ResponseShakeSessionList.class);
					
				} catch (Exception e) {
					Toast.makeText(context, "访问网络失败", Toast.LENGTH_SHORT).show();
					return;
				}finally{
					accessible = true;
				}
				if (responseList.rsNo == 100) {
					Intent intent = new Intent();
					if (responseList.rs.roundid == null) {
						Toast.makeText(context, "摇一摇下线", Toast.LENGTH_SHORT).show();
						
					} else if (responseList.rs.roundlist != null
							&& responseList.rs.roundlist.size() > 0
							&& responseList.rs.roundid != null) {
						intent.setClass(context, ShakeSessionActivity.class);
						intent.putExtra("ShakeSessionList", json);
						context.startActivity(intent);
					} else {
						intent.setClass(context, ShakeActivity.class);
						intent.putExtra("roundid", responseList.rs.roundid);
						context.startActivity(intent);
					}
				} else {
					Toast.makeText(context, "访问网络失败", Toast.LENGTH_SHORT).show();
				}	
			}
		});

	}
	
	abstract class DispatchIntent{
		public abstract void goToLogin();
	}
}
